#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""  
@Project : wupeiqi_async
@File : 12-多个MySQL连接.py
@Author : Royce
@Time : 2025/7/13 15:58  
@脚本说明 : 
"""
# !/usr/bin/env python
# -*- coding:utf-8 -*-
import asyncio
import aiomysql

from util.util import timer


async def execute(host, password):
    print("开始", host)
    # 网络IO操作：先去连接 host，遇到IO则自动切换任务，去连接另一个host实例
    conn = await aiomysql.connect(host=host, port=3306, user='root', password=password, db='mysql')

    # 网络IO操作：遇到IO会自动切换任务
    cur = await conn.cursor()

    # 网络IO操作：遇到IO会自动切换任务
    await cur.execute("SELECT Host,User FROM user")

    # 网络IO操作：遇到IO会自动切换任务
    result = await cur.fetchall()
    print(f'SQL语句执行结果:{result}')

    # 网络IO操作：遇到IO会自动切换任务
    await cur.close()
    conn.close()
    print("结束", host)


@timer('ms')
def async_test():
    task_list = [
        execute('192.168.88.66', "666888"),
        execute('192.168.88.66', "666888"),
        execute('192.168.88.66', "666888")
    ]

    asyncio.run(asyncio.wait(task_list))


@timer('ms')
def sync_test():
    task_list = [
        execute('192.168.88.66', "666888"),
        execute('192.168.88.66', "666888"),
        execute('192.168.88.66', "666888")
    ]

    for task in task_list:
        try:
            loop = asyncio.new_event_loop()  # 每次者单独创建一个事件循环
            asyncio.set_event_loop(loop)
            loop.run_until_complete(task)  # 等待异步任务执行完并返回结果
        except:
            pass


@timer('ms')
def biref_sync_test():
    addresses = [('192.168.88.66', "666888")] * 3  # 重复三次
    for addr, pwd in addresses:
        # 每次循环阻塞执行直到完成
        asyncio.run(execute(addr, pwd))


if __name__ == '__main__':
    # test()
    # async_test()
    sync_test()
    biref_sync_test()
